'use strict';

var mongoose = require('mongoose');
var User = mongoose.model('User');
var Logs = mongoose.model('Logs');
var config = require('../../config/env');
const SMSClient = require('@alicloud/sms-sdk');
const redis = require('../../util/redis');


const accessKeyId = 'LTAIBWCxtzIghz7h'
const secretAccessKey = 'oO26yOEwVSzLBrEYJtcdOGozex5avW'

/**
 * 获取验证码
 */
exports.getPhoneCode = function (req, res) {
    let smsClient = new SMSClient({accessKeyId, secretAccessKey});
    const PHONE_REGEXP = /^[1][3,4,5,7,8,6][0-9]{9}$/;
    let error_msg;
    const phoneNumber = req.body.phone || '';
    if (!PHONE_REGEXP.test(phoneNumber)) { // 手机号不合法
        error_msg = '手机号不合法';
        return res.status(422).send(error_msg);
    } else {
        redis.exists(phoneNumber).then((bool) => {
            if (bool == 0) {
                //生成随机验证码
                const code = 10000 + Math.floor(Math.random() * 89999);
                // 发送短信
                smsClient.sendSMS({
                    PhoneNumbers: phoneNumber,
                    SignName: '技能交换',
                    TemplateCode: 'SMS_130980138',
                    TemplateParam: `{"code":${code}}`
                }).then(function (code_res) {
                    let {Code} = code_res;
                    if (Code === 'OK') {
                        //处理返回参数
                        redis.setex(phoneNumber, 60, code);
                        res.status(200).json({
                            success_msg: '请求成功'
                        })
                    }
                }, function (err) {
                    console.log(err);
                });
            } else {
                error_msg = '请求频繁';
                res.status(422).send(error_msg);
            }
        });
    }
};
// 验证验证码
exports.confirmCode = function (req, res) {
    const phone = req.body.phone || '';
    const code = req.body.code || '';
    console.log(phone, code);
    let error_msg = '';
    if (phone.length !== 11 || code.length !== 5) {
        error_msg = '手机号或验证码不合法~';
        res.status(422).send(error_msg);
    } else {
        redis.get(phone, function (err, reply) {
            if (err) {
                error_msg = '请求频繁';
                res.status(422).send(error_msg);
            } else {
                if (`${code}` !== reply) {
                    console.log(reply);
                    error_msg = '验证码不正确';
                    res.status(422).send(error_msg);
                } else {
                    res.status(200).json({
                        success_msg: '验证成功'
                    });
                }
            }
        })
    }
};

exports.getMe = function (req, res) {
    var userId = req.user._id;
    User.findByIdAsync(userId).then(function (user) {
        return res.status(200).json(user.userInfo);
    }).catch(function (err) {
        return res.status(401).send();
    });
};
//后台获取用户列表
exports.getUserList = function (req, res, next) {
    var currentPage = (parseInt(req.query.currentPage) > 0) ? parseInt(req.query.currentPage) : 1;
    var itemsPerPage = (parseInt(req.query.itemsPerPage) > 0) ? parseInt(req.query.itemsPerPage) : 10;
    var startRow = (currentPage - 1) * itemsPerPage;

    var sortName = String(req.query.sortName) || "created";
    var sortOrder = req.query.sortOrder;
    if (sortOrder === 'false') {
        sortName = "-" + sortName;
    }


    User.countAsync().then(function (count) {
        return User.find({})
            .skip(startRow)
            .limit(itemsPerPage)
            .sort(sortName)
            .exec().then(function (userList) {
                return res.status(200).json({data: userList, count: count});
            })
    }).catch(function (err) {
        return next(err);
    })

}

//添加用户
exports.addUser = function (req, res) {
    let phone = req.body.phone ? req.body.phone.replace(/(^\s+)|(\s+$)/g, "") : '';
    const nickname = req.body.nickname ? req.body.nickname.replace(/(^\s+)|(\s+$)/g, "") :
        phone.substring(0, 3) + '****' + phone.substring(7, 11);
    const password = req.body.password;
    const confirmPassword = req.body.confirmPassword || '';
    const NICKNAME_REGEXP = /^[(\u4e00-\u9fa5)0-9a-zA-Z\_\s@*]+$/;
    const PHONE_REGEXP = /^[1][3,4,5,7,8,6][0-9]{9}$/;
    const PASSWORD_REGEXP = /^[0-9A-Za-z]{6,12}$/;
    let error_msg = undefined;
    if (nickname === '') {
        error_msg = "呢称不能为空";
    } else if (phone === '') {
        error_msg = "电话不能为空";
    } else if (nickname.length <= 2 || nickname.length > 15 || !NICKNAME_REGEXP.test(nickname)) {
        //不符合呢称规定.
        error_msg = "呢称不合法";
    } else if (phone.length !== 11 || !PHONE_REGEXP.test(phone)) {
        error_msg = "手机号不合法";
    } else if (!PASSWORD_REGEXP.test(password) || password != confirmPassword) {
        error_msg = "密码不合法";
    }
    if (error_msg) {
        return res.status(422).send(error_msg);
    }
    const newUser = new User({
        nickname: nickname,
        phone: phone,
        password: password
    });
    newUser.role = 'user';

    newUser.saveAsync().then(function (user) {
        // 增加一条log
        const newLogs = new Logs({
            uid: user._id,
            content: "创建新用户 " + (user.phone || user.nickname),
            type: "user"
        });
        newLogs.save();
        return res.status(200).json({success: true, user_id: user._id});
    }).catch(function (err) {
        if (err.errors && err.errors.nickname) {
            err = {error_msg: err.errors.nickname.message}
        }
        return res.status(500).send(err);
    });

}

//删除用户
exports.destroy = function (req, res, next) {
    var userId = req.user._id;

    if (String(userId) === String(req.params.id)) {
        return res.status(403).send({message: "不能删除自己已经登录的账号"});
    } else {
        User.findByIdAndRemoveAsync(req.params.id).then(function (user) {
            Logs.create({
                uid: userId,
                content: "删除用户" + (user.phone || user.nickname),
                type: "user"
            });
            return res.status(200).send({success: true});
        }).catch(function (err) {
            return next(err);
        });
    }
}

//更新用户
exports.updateUser = function (req, res) {
    //被编辑人
    var editUserId = req.params.id;
    var nickname = req.body.nickname ? req.body.nickname.replace(/(^\s+)|(\s+$)/g, "") : '';
    var phone = req.body.phone ? req.body.phone.replace(/(^\s+)|(\s+$)/g, "") : '';
    var NICKNAME_REGEXP = /^[(\u4e00-\u9fa5)0-9a-zA-Z\_\s@]+$/;
    var phone_REGEXP = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
    var error_msg;
    if (nickname === '') {
        error_msg = "呢称不能为空";
    } else if (phone === '') {
        error_msg = "电话不能为空";
    } else if (nickname.length <= 2 || nickname.length > 15 || !NICKNAME_REGEXP.test(nickname)) {
        //不符合呢称规定.
        error_msg = "呢称不合法";
    } else if (phone.length <= 4 || phone.length > 30 || !phone_REGEXP.test(phone)) {
        error_msg = "邮箱地址不合法";
    }
    if (error_msg) {
        return res.status(422).send({error_msg: error_msg});
    }

    User.findByIdAsync(editUserId).then(function (user) {
        user.nickname = req.body.nickname;
        user.phone = req.body.phone.toLowerCase();
        if (req.body.status) {
            user.status = req.body.status;
        }
        if (req.body.newPassword) {
            user.password = req.body.newPassword;
        }
        return user.saveAsync().then(function (user) {
            Logs.create({
                phone: req.user._id,
                content: "编辑用户" + (user.phone || user.nickname),
                type: "user"
            });
            return res.status(200).json({success: true, user_id: user._id});
        });

    }).catch(function (err) {
        if (err.errors.nickname) {
            err = {error_msg: err.errors.nickname.message}
        }
        return res.status(500).send(err);
    });
};

//前台获取用户社交账号绑定情况.
exports.getUserProvider = function (req, res, next) {
    User.findByIdAsync(req.user._id).then(function (user) {
        return res.status(200).json({data: user.providerInfo});
    }).catch(function (err) {
        return next(err);
    })
};

//获取用户信息
exports.getUserInfo = function (req, res, next) {
    let error_msg = '';
    if (!req.query.userId) {
        error_msg = '查询有误';
        return res.status(422).send(error_msg);
    }

    User.findByIdAsync(req.query.userId).then(function (user) {
        return res.status(200).json({data: user.overview});
    }).catch(function (err) {
        return next(err);
    })
};

// 添加关注
exports.addStar = function (req, res, next) {
    let error_msg = '';
    const userId = req.user._id;
    const sourceId = req.body.sourceId;
    const targetId = req.body.targetId;
    console.log(userId, sourceId);
    if (userId != sourceId) { // 简单处理
        error_msg = '请通过正确路径关注';
        return res.status(422).send(error_msg);
    } else if (sourceId === targetId) {
        error_msg = '不能给自己添加关注';
        return res.status(422).send(error_msg);
    }
    User.findByIdAsync(targetId).then(function (targetUser) {
        let fansList = targetUser.fansList;
        if (!!fansList.find(item => item === sourceId)) {
            error_msg = '不能给自己添加关注';
            return res.status(403).send(error_msg);
        } else {
            targetUser.fansList.push(sourceId);
            return targetUser.saveAsync();
        }
    }).then((TUser) => {
        if (TUser) {
            return User.findByIdAsync(sourceId).then(function (sourceUser) {
                let starsList = sourceUser.starsList;
                if (!!starsList.find(item => item === targetId)) {
                    error_msg = '已关注';
                    return res.status(403).send(error_msg);
                } else {
                    sourceUser.starsList.push(TUser._id);
                    return sourceUser.saveAsync();
                }
            })
        }
    }).then((SUser) => {
        if (SUser) {
            return res.status(200).send('添加成功');
        }
    }).catch(function (err) {
        return res.status(401).send();
    });
};

// 获取关注列表
exports.getStarsList = function (req, res, next) {
    const userId = req.params.id;
    User.findByIdAsync(userId).then((user) => {
        let array = [];
        for (let i = 0; i < user.starsList.length; i++) {
            array.push(User.findByIdAsync(user.starsList[i]));
        }
        return Promise.all(array).then((starsList) => {
            starsList = starsList.map(item => item.overview);
            return res.status(200).json({data: starsList, count: user.starsList.length});
        }).catch((err) => {
            return res.status(422).send('查询失败');
        });
    }).catch((err) => {
        return res.status(422).send('查询失败');
    });
};
// 获取粉丝列表
exports.getFansList = function (req, res, next) {
    const userId = req.user && req.user._id;
    User.findByIdAsync(userId).then((user) => {
        let array = [];
        for (let i = 0; i < user.fansList.length; i++) {
            array.push(User.findByIdAsync(user.fansList[i]));
        }
        return Promise.all(array).then((fansList) => {
            fansList = fansList.map(item => item.overview);
            return res.status(200).json({data: fansList, count: user.fansList.length});
        }).catch((err) => {
            return res.status(422).send('查询失败');
        });
    }).catch((err) => {
        return res.status(422).send('查询失败');
    });
};

//获取第三方登录列表.
exports.getSnsLogins = function (req, res, next) {
    if (config.snsLogins) {
        return res.status(200).json({success: true, data: config.snsLogins});
    } else {
        return res.status(404).send();
    }
}